/*
 * Copyright (c) 2010 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package vn.pyco.prez.tapestry.services.comet.services;

import java.util.HashMap;
import java.util.Map;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.ConfigurableServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.java.annotation.Configure;
import org.cometd.java.annotation.Listener;
import org.cometd.java.annotation.Service;
import org.cometd.java.annotation.Session;
import org.cometd.server.authorizer.GrantAuthorizer;

import vn.pyco.prez.dao.DaoManager;

@Service("remoteControlService")
public class RemoteControlService {
	@SuppressWarnings("unused")
	@Inject
	private BayeuxServer bayeux;
   
	@Session
	private ServerSession serverSession;
	
	@InjectService("clientSessionManager")
	private DaoManager<ServerSession> _clientSessionManager;
	
	@Configure({"/service/prez/control"})
	public void configure(ConfigurableServerChannel channel){
		channel.setLazy(false);
	    channel.addAuthorizer(GrantAuthorizer.GRANT_PUBLISH);
	    channel.addAuthorizer(GrantAuthorizer.GRANT_SUBSCRIBE);
	}
	   
	@Listener("/service/prez/control")
	public void echo(ServerSession remote, ServerMessage.Mutable message){
		Map<String, Object> input = message.getDataAsMap();
	    String command = (String)input.get("command");
	    
	    if(command.equals("connect")){
		    String taskId = (String)input.get("taskId");
		    _clientSessionManager.save(taskId, remote);
	    }
	    
	    if(command.equals("remotecontrol")){
		    String taskId = (String)input.get("taskId");
		    String action = (String)input.get("action");
		    ServerSession client = _clientSessionManager.getById(taskId);
		    if(client != null) {
		    	Map<String, Object> output = new HashMap<String, Object>();
		        output.put("action",action);
		        client.deliver(serverSession, "/prez/control", output, null);
	        }
	    }
	}
}
